import type { DynamicProps, FormActionType, Nullable } from '../../../BasicForm/src/types/form';
import { ref, toRaw, unref, watch, type WatchStopHandle } from 'vue';
import { getDynamicProps } from '../../../BasicForm/src/common/gloab';
import { ElMessage, type PaginationProps } from 'element-plus';
import type { PaginationPropsType } from '../types/pagination';
import type { BasicTableProps, FetchParams, TableActionType } from '../types/table';
import type { Recordable } from '#/types/global';

type Props = Partial<DynamicProps<BasicTableProps>>;
type UseTableMethod = TableActionType & {
  getForm: () => FormActionType;
};

export function useVxeTable(
  tableProps?: Props,
): [(instance: TableActionType, formInstance: UseTableMethod) => void, UseTableMethod] {
  const tableRef = ref<Nullable<TableActionType>>(null);
  const loadedRef = ref<Nullable<boolean>>(false);
  const formRef = ref<Nullable<UseTableMethod>>(null);

  let stopWatch: WatchStopHandle;

  //  设置初始值
  function register(instance: TableActionType, formInstance: UseTableMethod) {
    // onUnmounted(() => {
    //   tableRef.value = null;
    //   loadedRef.value = null;
    // });
    if (unref(loadedRef) && instance === unref(tableRef)) return;

    tableRef.value = instance;
    formRef.value = formInstance;
    tableProps && instance.setProps(getDynamicProps(tableProps));
    loadedRef.value = true;
    // 停止监听
    stopWatch?.();
    stopWatch = watch(
      () => tableProps,
      () => {
        tableProps && instance.setProps(getDynamicProps(tableProps));
      },
      {
        immediate: true,
        deep: true,
      },
    );
  }
  //   获取表格实例
  function getTableInstance(): TableActionType {
    const table = unref(tableRef);
    if (!table) {
      ElMessage({
        message: '尚未获得表格实例，请确保在执行表格操作时表格已存在！',
        type: 'error',
        duration: 2000,
      });
    }
    return table as TableActionType;
  }

  const methods: TableActionType & {
    getForm: () => FormActionType;
  } = {
    // 更新table
    reload: async (opt?: FetchParams) => {
      return getTableInstance().reload(opt);
    },
    setProps: (props: Partial<BasicTableProps>) => {
      getTableInstance().setProps(props);
    },
    getForm: () => {
      return unref(formRef) as unknown as FormActionType;
    },
    getSize: () => {
      return toRaw(getTableInstance().getSize());
    },
    setShowForm: async (show: boolean) => {
      getTableInstance().setShowForm(show);
    },
    getShowForm: () => {
      return toRaw(getTableInstance().getShowForm());
    },
    // setSelectedRows: (rows: Recordable[]) => {
    //   return toRaw(getTableInstance().setSelectedRows(rows))
    // },
    getLoading: () => {
      return getTableInstance().getLoading();
    },
    setLoading: (loading: boolean) => {
      getTableInstance().setLoading(loading);
    },
    getDataSource: () => {
      return getTableInstance().getDataSource();
    },
    getRawDataSource: () => {
      return getTableInstance().getRawDataSource();
    },
    // getColumns: ({ ignoreIndex = false }: { ignoreIndex?: boolean } = {}) => {
    //   const columns = getTableInstance().getColumns({ ignoreIndex }) || []
    //   return toRaw(columns)
    // },
    // setColumns: (columns: BasicColumn[]) => {
    //   getTableInstance().setColumns(columns)
    // },
    setTableData: (values: any[]) => {
      return getTableInstance().setTableData(values);
    },
    setPagination: (info: Partial<PaginationProps | PaginationPropsType>) => {
      return getTableInstance().setPagination(info);
    },
    deleteSelectRowByKey: (key: string) => {
      getTableInstance().deleteSelectRowByKey(key);
    },
    // getSelectRowKeys: () => {
    //   return toRaw(getTableInstance().getSelectRowKeys())
    // },
    // getSelectRows: () => {
    //   return toRaw(getTableInstance().getSelectRows())
    // },
    // clearSelectedRowKeys: () => {
    //   getTableInstance().clearSelectedRowKeys()
    // },
    // setSelectedRowKeys: (keys: string[] | number[]) => {
    //   getTableInstance().setSelectedRowKeys(keys)
    // },
    getPagination: () => {
      return getTableInstance().getPagination();
    },
    // updateTableData: (index: number, key: string, value: any) => {
    //   return getTableInstance().updateTableData(index, key, value)
    // },
    // deleteTableDataRecord: (rowKey: string | number | string[] | number[]) => {
    //   return getTableInstance().deleteTableDataRecord(rowKey)
    // },
    insertTableDataRecord: (record: Recordable | Recordable[], index?: number) => {
      return getTableInstance().insertTableDataRecord(record, index);
    },
    updateTableDataRecord: (rowKey: string | number, record: Recordable) => {
      return getTableInstance().updateTableDataRecord(rowKey, record);
    },
    // findTableDataRecord: (rowKey: string | number) => {
    //   return getTableInstance().findTableDataRecord(rowKey)
    // },
    // getRowSelection: () => {
    //   return toRaw(getTableInstance().getRowSelection())
    // },
    // getCacheColumns: () => {
    //   return toRaw(getTableInstance().getCacheColumns())
    // },

    setShowPagination: async (show: boolean) => {
      getTableInstance().setShowPagination(show);
    },
    getShowPagination: () => {
      return toRaw(getTableInstance().getShowPagination());
    },
    // expandAll: () => {
    //   getTableInstance().expandAll()
    // },
    // expandRows: (keys: string[]) => {
    //   getTableInstance().expandRows(keys)
    // },
    // collapseAll: () => {
    //   getTableInstance().collapseAll()
    // },
    // scrollTo: (pos: string) => {
    //   getTableInstance().scrollTo(pos)
    // },
    getVxeTableRef: () => {
      return getTableInstance().getVxeTableRef() as any;
    },
  };

  return [register, methods];
}
